#ifndef CHATWINDOW_H
#define CHATWINDOW_H

#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QTimer>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QVBoxLayout>
#include <QPainter>
#include <QPixmap>
#include <QStackedWidget>
#include <QHBoxLayout>
#include <QDateTime>
#include <QEvent>
#include <QKeyEvent>
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlock>
#include <QTextBlockFormat>
#include <QTextDocumentFragment>
#include <QComboBox>
#include <QFontComboBox>
#include <QMessageBox>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QAudioFormat>
#include <QElapsedTimer>
#include <QFile>
#include <QThread>
#include <QMutexLocker>

class MusicPlayerThread : public QThread
{
    Q_OBJECT
public:
    explicit MusicPlayerThread(QObject *parent = nullptr);
    ~MusicPlayerThread();
    
    void run() override;
    void setVolume(float volume);
    void play();
    void pause();
    void stop();
    
signals:
    void errorOccurred(const QString &error);
    
private:
    QMediaPlayer *mediaPlayer;
    QAudioOutput *audioOutput;
    bool m_playing;
    float m_volume;
    QMutex m_mutex;
};

class ChatWindow : public QWidget
{
    Q_OBJECT

public:
    explicit ChatWindow(QWidget *parent = nullptr);
    ~ChatWindow();

private slots:
    void sendMessage();
    void updateTime();
    void handleNetworkReply(QNetworkReply *reply);
    void toggleMusic();
    void adjustVolume(int value);
    void handleMusicError(const QString &error);

protected:
    void paintEvent(QPaintEvent *event) override;
    bool eventFilter(QObject *watched, QEvent *event) override;

private:
    void setupUI();
    void setupNetwork();
    void setupModelApiKey();
    QNetworkRequest createRequest(const QString& apiKey, const QString& model);
    QJsonObject createJsonPayload(const QString& message, const QString& model);

    QTextEdit *chatDisplay;
    QLineEdit *messageInput;
    QPushButton *sendButton;
    QLabel *timeLabel;
    QTimer *timer;
    QNetworkAccessManager *networkManager;
    QString apiKey;
    QTextCharFormat format;
    QComboBox *modelComboBox;
    QString prefix = "亲爱的蕊蕊宝宝，";

    MusicPlayerThread *musicThread;
    QPushButton *musicToggleButton;
    QSlider *volumeSlider;
    QElapsedTimer performanceTimer;
};

#endif // CHATWINDOW_H